package com.fenghui.doubantop.utils;

import cn.hutool.http.HttpUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseUtils {
    /**
     * 用户session常量
     */

    public final static String USER_SESSION = "userSession";

    /**
     * 分页常量，每页显示数目
     */
    public final static int PAGE_SIZE = 10;

    /**
     * 获取格式化后的当前日期+时间
     * @return
     */
    public static String  getCurrentData() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateFormat.format(date));
        return dateFormat.format(date);
    }

    /**
     * 通过url获取文件名称
     * @param url
     * @return
     */
    public static String extractNumber(String url) {

        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(url);
        String fileName = "";
        if (matcher.find()) {
            fileName = matcher.group();
        }
        return fileName;
    }

    /**
     * 定义sqlSessionFactory 成员变量
     */
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 通过静态代码块 加载mybatis核心配置文件并创建sqlSessionFactory
     */
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取SqlSession
     * @return
     */
    public static SqlSession getSqlSession() {


        return sqlSessionFactory.openSession();
    }


    /**
     * 通过URL下载文件工具类
     * @param imgUrl 下载文件的地址
     * @param path  文件保存路径
     * @param imgName 保存的文件名
     *
     */
    public static void downloadImg(String imgUrl, String path,String imgName) {

        String fileName ="."+ File.separator+ "poster"+File.separator+path +File.separator+ imgName + ".jpg";
        File file = HttpUtil.downloadFileFromUrl(imgUrl, fileName);
        if (file != null) {
            System.out.println("已成功下载图片:" + fileName);
        }


    }

    public static void downloadImg(String imgUrl, String path) {

        File file = HttpUtil.downloadFileFromUrl(imgUrl, path);
        if (file != null) {
            System.out.println("已成功下载图片:" + path);
        }

    }
}
